import MainLayout from "./layout";
import { useRouter } from "next/router";
import React, { useState, useEffect, Fragment } from "react";
import Handsontable from "handsontable";
import { HotTable } from "@handsontable/react";
import "handsontable/languages/zh-CN";
import { Button, message, Space } from "antd";

export default function Log() {
  const router = useRouter();

  const data = [

    [
       "上级部门部署的工作 ",
       "党风廉政建设工作",
       "规范加油卡管理",
       "1、开展自查",
       "2020-11-20",
       2,
       "标准1",
    ],
    [
       null,
       null,
       null,
       "2、完成自查自纠报告",
       "2020-11-10",
       2,
       null,
    ],
    [
       null,
       null,
       null,
       "2、完成自查自纠报告",
       null,
       2,
       null,
    ],
    [
       '大类1',
       '类型2',
       '类型3',
       "2、完成自查自纠报告",
       null,
       2,
       null,
    ],
    [
       null,
       '类型2',
       '类型3',
       "2、完成自查自纠报告",
       null,
       2,
       null,
    ],
  ];

  const dataSpan = new Array(data.length);

  data.forEach((item, index) => {
    dataSpan[index] = new Array(11).fill(1);
    Object.keys(item).forEach((innerItem, innerIndex) => {
      // console.log(index, innerItem, innerIndex, item[innerItem]);
      if (index > 0) {
        if (!item[innerItem]) {
          for (let i = index - 1; i > -1; i--) {
            if (data[i][innerItem]) {
              dataSpan[i][innerIndex] += 1;
              return;
            }
          }
        }
      }
    });
  });
  // console.log(dataSpan);

  const mergeData = [];
  dataSpan.forEach((item, index) => {
    item.forEach((innerItem, innerIndex) => {
      if (innerItem > 1) {
        mergeData.push({
          row: index,
          col: innerIndex,
          rowspan: innerItem,
          colspan: 1,
        });
      }
    });
  });
  // console.log(mergeData);
  const initialSetting = {
    // colHeaders: true,
    rowHeaders: true,
    colHeaders: [
      "一级指标",
      "二级指标",
      "三级指标",
      "关键步骤",
      "完成时限",
      "分值",
      "评分标准",
      "目标来源",
      "责任部门",
      "分管领导/责任人",
      "有关责任人",
    ],
    contextMenu: true,
    mergeCells: mergeData,
    manualColumnResize: true,
    manualRowResize: true,
    width: "100%",
    height: 680,
    className: "htMiddle", //https://handsontable.com/docs/8.1.0/demo-alignment.html
    minSpareRows: 1,
    rowHeights: 36,
    colWidths: [200, 200, 200, 260, 120, 80, 180, 220, 200, 180, 180],
    contextMenu: [
      "row_above",
      "row_below",
      "clear_column",
      "remove_row",
      "---------",
      "mergeCells",
      "make_read_only",
      "alignment",
    ],
    columns: [
      {
        data: 0,
        allowEmpty: false,
      },
      {
        data: 1,
      },
      {
        data: 2,
      },
      {
        data: 3,
      },
      {
        data: 4,
        type: "date",
        dateFormat: "YYYY-MM-DD",
        datePickerConfig: {
          i18n: {
            previousMonth: "上月",
            nextMonth: "下月",
            months: [
              "一月",
              "二月",
              "三月",
              "四月",
              "五月",
              "六月",
              "七月",
              "八月",
              "九月",
              "十月",
              "十一月",
              "十二月",
            ],
            weekdays: [
              "星期日",
              "星期一",
              "星期二",
              "星期三",
              "星期四",
              "星期五",
              "星期六",
            ],
            weekdaysShort: [
              "周日",
              "周一",
              "周二",
              "周三",
              "周四",
              "周五",
              "周六",
            ],
          },
        },
      },
      {
        data: 5,
        type: "numeric",
      },
      {
        data: 6,
        editor: "select",
        selectOptions: ["标准1", "标准2", "标准3", "标准4"],
      },
      {
        data: 7,
        editor: "select",
        selectOptions: ["目标来源1", "目标来源2", "目标来源3", "目标来源4"],
      },
      {
        data: 8,
        editor: "select",
        selectOptions: ["责任部门1", "责任部门2", "责任部门3", "责任部门4"],
      },
      {
        data: 9,
        editor: "select",
        selectOptions: [
          "分管领导/责任人1",
          "分管领导/责任人2",
          "分管领导/责任人3",
          "分管领导/责任人4",
        ],
      },
      {
        data: 10,
        editor: "select",
        selectOptions: [
          "有关责任人1",
          "有关责任人2",
          "有关责任人3",
          "有关责任人4",
        ],
      },
    ],
    data,
    licenseKey: "non-commercial-and-evaluation",
  };
  const [setting, setSetting] = useState(initialSetting);
  const hotTableComponent = React.createRef();

  let tmp = new Array(data.length);
  for(let i=0;i<data.length;i++) {
    tmp[i] = new Array(11).fill(true);
  }

  const [isValid, setIsValid] = useState(tmp);



  const validateCallback = (isValided, value, row,col) => {
    console.log(isValided, value,row,col);

    let tmp = isValid;
    if(row>tmp.length-1) {
      for(let i = row;i>tmp.length-2;i--) {
        console.log(i)
        tmp.push(new Array(11).fill(true))
      }
    }
    tmp[row][col] = isValided

    console.log(tmp)
    setIsValid(tmp);


    return isValided;
    // if (!isValided) message.info(value + "不正确");
  };

  const removeCallback = (index,amount, data) =>{
    console.log(index,amount,data)

    let tmp = isValid;
    tmp.splice(index,amount);
    console.log(tmp)
    // setTimeout(()=>{
      setIsValid(tmp);
    
    // },0)
  }

  useEffect(() => {
    Handsontable.hooks.add(
      "afterValidate",
      [validateCallback],
      hotTableComponent.current.hotInstance
    );

    Handsontable.hooks.add(
      "afterRemoveRow",
      [removeCallback],
      hotTableComponent.current.hotInstance
    );
  }, []);

  // const [result, setResult] = useState();

  const checkWholeValid = ()=>{
    let result = true;
    isValid.forEach(item=>{
      item.forEach(inner=>{
        if(!inner) {
          result = false;
          return;
        }
      })
    })

    return result;
  }

  const getTableData = () => {
    let tmp;
    if (hotTableComponent.current) {
      tmp = hotTableComponent.current.hotInstance.getData();
      console.log(hotTableComponent.current.hotInstance);
    }

    console.log(isValid);
    if (!checkWholeValid()) {
      message.error("数据校验错误");
    }

    tmp.splice(tmp.length - 1, 1); // 删除最后一行
    console.log(tmp);
    // setResult(tmp);
    message.info(tmp);
  };

  return (
    <Fragment>
      <Space style={{ marginBottom: "10px" }}>
        <Button
          type="primary"
          //
          onClick={() => setSetting({ ...initialSetting, data: [], mergeCells:[] })}
        >
          新建
        </Button>
        <Button
          type="primary"
          // style={{ marginBottom: "10px" }}
          onClick={() => getTableData()}
        >
          获取数据
        </Button>
      </Space>
      {/* {result?<div>{result}</div>:''} */}

      <HotTable
        ref={hotTableComponent}
        language="zh-CN"
        settings={setting}
        style={{ width: "100%" }}
      />
    </Fragment>
  );
}
/*

上级部门部署的工作      党风廉政建设工作                       
                                      纠治“四风”
                                      数据信息报送
*/
